package com.itheima.crops.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.crops.dao.DiseaseMapper;
import com.itheima.crops.dao.PcropsIndexMapper;
import com.itheima.crops.dao.PcropsMapper;
import com.itheima.crops.dao.IndexMapper;
import com.itheima.crops.pojo.*;
import com.itheima.crops.service.IndexService;
import com.itheima.crops.service.PcropsService;
import com.itheima.crops.utils.CommonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PcropsServiceImpl implements PcropsService {
    @Autowired
    private PcropsMapper pcropsMapper;
    @Autowired
    private IndexMapper indexMapper;
    @Autowired
    private DiseaseMapper diseaseMapper;
    @Autowired
    private PcropsIndexMapper pcropsIndexMapper;
    @Autowired
    private IndexService indexService;

    /**
     * 条件+分页查询
     * @param searchMap 查询条件
     * @param page 页码
     * @param size 页大小
     * @return 分页结果
     */
    @Override
    public Page<Pcrops> findPage(Map<String,Object> searchMap, int page, int size){
        PageHelper.startPage(page,size);
        Example example = createExample(searchMap);
        return (Page<Pcrops>)pcropsMapper.selectByExample(example);
    }

    /**
     * 农作物全查
     * @return
     */
    @Override
    public List<Pcrops> findAll() {
        List<Pcrops> pcropsList = pcropsMapper.selectAll();
        return pcropsList;
    }

    /**
     * 农作物根据id查询并查询关联表
     * @param id
     * @return
     */
    @Override
    public Crops findById(Integer id) {
        Crops crops = new Crops();
        Pcrops pcrops = pcropsMapper.selectByPrimaryKey(id);
        if(pcrops == null) {
            throw new RuntimeException("农作物不存在");
        }
        crops.setPcrops(pcrops);

        List<PcropsIndexInfo> pcropsIndexInfos =new ArrayList<>();
        //查农作物与指标关联表
        List<PcropsIndex> pcropsIndexs = pcropsIndexMapper.findPcropsIndexsByCid(id);
        if(pcropsIndexs != null && pcropsIndexs.size() > 0) {
            for (PcropsIndex pcropsIndex : pcropsIndexs) {
                PcropsIndexInfo pcropsIndexInfo = new PcropsIndexInfo();
                pcropsIndexInfo.setIid(pcropsIndex.getIid());
                Index index = indexMapper.selectByPrimaryKey(pcropsIndex.getIid());
                pcropsIndexInfo.setName(index.getName());
                pcropsIndexInfo.setSuit(pcropsIndex.getSuit());
                pcropsIndexInfo.setUnit(index.getUnit());
                pcropsIndexInfos.add(pcropsIndexInfo);
            }
            crops.setPcropsIndexInfos(pcropsIndexInfos);
        }

        List<Disease> diseases = new ArrayList<>();
        //查农作物与病虫害关联表
        List<Integer> dids = pcropsMapper.findDidsByCid(id);
        if(dids != null && dids.size() > 0) {
            for (Integer did : dids) {
                Disease disease = diseaseMapper.selectByPrimaryKey(did);
                diseases.add(disease);
            }
            crops.setDiseases(diseases);
        }

        return crops;
    }

    /**
     * 农作物根据id查询
     * @param id
     * @return
     */
    @Override
    public Pcrops findById1(Integer id) {
        Pcrops pcrops = pcropsMapper.selectByPrimaryKey(id);
        if(pcrops == null) {
            throw new RuntimeException("农作物不存在");
        }
        return pcrops;
    }

    /**
     * 查农作物与指标关联关系
     * @param id 农作物id
     * @return
     */
    @Override
    public List<PcropsIndexInfo> pcropsIndexInfoList(Integer id) {
        Pcrops pcrops = pcropsMapper.selectByPrimaryKey(id);
        if(pcrops == null) {
            throw new RuntimeException("农作物不存在");
        }
        List<PcropsIndexInfo> pcropsIndexInfos =new ArrayList<>();
        //查农作物与指标关联表
        List<PcropsIndex> pcropsIndexs = pcropsIndexMapper.findPcropsIndexsByCid(id);
        if(pcropsIndexs != null && pcropsIndexs.size() > 0) {
            for (PcropsIndex pcropsIndex : pcropsIndexs) {
                PcropsIndexInfo pcropsIndexInfo = new PcropsIndexInfo();
                Long iid = pcropsIndex.getIid();
                System.out.println("iid = " + iid);
                if(iid != null) {
                    Index index = indexMapper.selectByPrimaryKey(iid);
                    pcropsIndexInfo.setIid(iid);
                    pcropsIndexInfo.setName(index.getName());
                    pcropsIndexInfo.setUnit(index.getUnit());
                    pcropsIndexInfo.setSuit(pcropsIndex.getSuit());
                    pcropsIndexInfos.add(pcropsIndexInfo);
                }

            }
        }
        return pcropsIndexInfos;
    }

    /**
     * 查农作物与病虫害关联表
     * @param id
     * @return
     */
    @Override
    public List<Disease> diseaseList(Integer id) {
        Pcrops pcrops = pcropsMapper.selectByPrimaryKey(id);
        if(pcrops == null) {
            throw new RuntimeException("农作物不存在");
        }
        List<Disease> diseases = new ArrayList<>();
        //查农作物与病虫害关联表
        List<Integer> dids = pcropsMapper.findDidsByCid(id);
        if(dids != null && dids.size() > 0) {
            for (Integer did : dids) {
                Disease disease = diseaseMapper.selectByPrimaryKey(did);
                diseases.add(disease);
            }
        }
        return diseases;
    }

    /**
     * 新增农作物基本信息并返回农作物id
     * @param pcrops
     * @return
     */
    @Transactional
    @Override
    public Integer add(Pcrops pcrops) {
        pcropsMapper.insertSelective(pcrops);
        Map<String, Object> searchMap = CommonUtils.convertToMap(pcrops);
        Example example = createExample(searchMap);
        List<Pcrops> pcropsList = pcropsMapper.selectByExample(example);
        Pcrops one = pcropsList.get(0);
        return one.getId();
    }

    /**
     * 添加农作物与指标的关联关系
     * @param cid
     * @param pcropsIndexInfoVO
     */
    @Transactional
    @Override
    public void addPcropsIndexRel(Long cid,PcropsIndexInfoVO pcropsIndexInfoVO) {
        Pcrops pcrops = pcropsMapper.selectByPrimaryKey(cid);
        if(pcrops == null) {
            throw new RuntimeException("农作物不存在");
        }
        if(pcropsIndexInfoVO != null) {
            List<PcropsIndexInfo> pcropsIndexInfos = pcropsIndexInfoVO.getPcropsIndexInfos();
            if(pcropsIndexInfos != null && pcropsIndexInfos.size() > 0) {
                for (PcropsIndexInfo pcropsIndexInfo : pcropsIndexInfos) {
                    PcropsIndex pcropsIndex = new PcropsIndex();
                    pcropsIndex.setIid(pcropsIndexInfo.getIid());
                    pcropsIndex.setCid(cid);
                    pcropsIndex.setSuit(pcropsIndexInfo.getSuit());
                    pcropsIndexMapper.insertSelective(pcropsIndex);
                }
            }
        }
    }

    /**
     * 添加农作物与病虫害的关联关系
     * @param cid
     * @param dids
     */
    @Override
    public void addPcropsDiseaseRel(Long cid,Long[] dids) {
        Pcrops pcrops = pcropsMapper.selectByPrimaryKey(cid);
        if(pcrops == null) {
            throw new RuntimeException("农作物不存在");
        }
        if(dids != null && dids.length > 0) {
            for (Long did : dids) {
                pcropsMapper.addPcropsDiseaseRel(cid,did);
            }
        }
    }

    /**
     * 修改农作物基本信息
     * @param pcrops
     */
    @Transactional
    @Override
    public void Update(Pcrops pcrops) {
        Pcrops pcrops1 = pcropsMapper.selectByPrimaryKey(pcrops.getId());
        if(pcrops1 == null) {
            throw new RuntimeException("农作物不存在");
        }
        pcropsMapper.updateByPrimaryKey(pcrops);
    }

    /**
     * 修改农作物与指标关联关系
     * @param cid
     * @param pcropsIndexInfoVO
     */
    @Transactional
    @Override
    public void updatePcropsIndexRel(Long cid,PcropsIndexInfoVO pcropsIndexInfoVO) {
        Pcrops pcrops = pcropsMapper.selectByPrimaryKey(cid);
        if(pcrops == null) {
            throw new RuntimeException("农作物不存在");
        }
        pcropsIndexMapper.deletePcropsIndexRel(cid);
        if(pcropsIndexInfoVO != null) {
            List<PcropsIndexInfo> pcropsIndexInfos = pcropsIndexInfoVO.getPcropsIndexInfos();
            if(pcropsIndexInfos != null && pcropsIndexInfos.size() > 0) {
                for (PcropsIndexInfo pcropsIndexInfo : pcropsIndexInfos) {
                    Long iid = pcropsIndexInfo.getIid();
                    PcropsIndex pcropsIndex = new PcropsIndex();
                    pcropsIndex.setCid(cid);
                    pcropsIndex.setIid(iid);
                    pcropsIndex.setSuit(pcropsIndexInfo.getSuit());
                    pcropsIndexMapper.insertSelective(pcropsIndex);
                }
            }
        }
    }

    /**
     * 修改农作物与病虫害关联关系
     * @param cid
     * @param dids
     */
    @Transactional
    @Override
    public void updatePcropsDiseaseRel(Long cid,Long[] dids) {
        Pcrops pcrops = pcropsMapper.selectByPrimaryKey(cid);
        if(pcrops == null) {
            throw new RuntimeException("农作物不存在");
        }
        pcropsMapper.deletePcropsDiseaseRel(cid);
        if(dids != null && dids.length > 0) {
            for (Long did : dids) {
                pcropsMapper.addPcropsDiseaseRel(cid,did);
            }
        }
    }

    /**
     * 删除农作物以及农作物与农作物指标关联关系，农作物与病虫害关联关系
     * @param id
     */
    @Transactional
    @Override
    public void delete(Long id) {
        Pcrops pcrops = pcropsMapper.selectByPrimaryKey(id);
        if(pcrops == null) {
            throw new RuntimeException("农作物不存在");
        }

        Map<String,String> hashMap = new HashMap<>();
        hashMap.put("name",pcrops.getName());
        hashMap.put("stage",pcrops.getStage());

        List<Crops> cropsList = pcropsMapper.findCropsByNameAndStage(hashMap);
        if(cropsList != null && cropsList.size() > 0) {
            throw new RuntimeException("该农作物已种植");
        }

        pcropsIndexMapper.deletePcropsIndexRel(id);
        pcropsMapper.deletePcropsDiseaseRel(id);
        pcropsMapper.deleteByPrimaryKey(id);
    }

    /**
     * 构建查询对象
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap){
        Example example=new Example(Pcrops.class);
        Example.Criteria criteria = example.createCriteria();
        if(searchMap!=null){
            // 主键
            if(searchMap.get("id")!=null && !"".equals(searchMap.get("id"))){
                criteria.andEqualTo("id",searchMap.get("id"));
            }
            // 农作物名称
            if(searchMap.get("name")!=null && !"".equals(searchMap.get("name"))){
                criteria.andLike("name", "%"+searchMap.get("name")+"%");
            }
            // 农作物别名
            if(searchMap.get("alias")!=null && !"".equals(searchMap.get("alias"))){
                criteria.andLike("alias", "%"+searchMap.get("alias")+"%");
            }
            // 农作物界门纲目科属种
            if(searchMap.get("Lauraceae")!=null && !"".equals(searchMap.get("Lauraceae"))){
                criteria.andLike("Lauraceae", "%"+searchMap.get("Lauraceae")+"%");
            }

            //农作物简介
            if(searchMap.get("synopsis")!=null && !"".equals(searchMap.get("synopsis"))){
                criteria.andLike("synopsis", "%"+searchMap.get("synopsis")+"%");
            }

            //农作物分布区域
            if(searchMap.get("region")!=null && !"".equals(searchMap.get("region"))){
                criteria.andLike("region", "%"+searchMap.get("region")+"%");
            }

            //农作物外观
            if(searchMap.get("aspect")!=null && !"".equals(searchMap.get("aspect"))){
                criteria.andLike("aspect", "%"+searchMap.get("aspect")+"%");
            }

            //农作物栽培技术
            if(searchMap.get("cultivation")!=null && !"".equals(searchMap.get("cultivation"))){
                criteria.andLike("cultivation", "%"+searchMap.get("cultivation")+"%");
            }

            //农作物生长阶段
            if(searchMap.get("stage")!=null && !"".equals(searchMap.get("stage"))){
                criteria.andLike("stage", "%"+searchMap.get("stage")+"%");
            }

        }
        return example;
    }
}
